package cn.anecansaitin.industrialization_expansion.common.cap.provider;

import cn.anecansaitin.industrialization_expansion.api.common.cap.IModifiedAttribute;
import cn.anecansaitin.industrialization_expansion.api.common.cap.IModuleStorage;
import cn.anecansaitin.industrialization_expansion.common.cap.*;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class ModifiedToolProvider implements ICapabilityProvider {
    private final ItemStack stack;
    private LazyOptional<IEnergyStorage> energy;
    private LazyOptional<IModuleStorage> module;
    private LazyOptional<IModifiedAttribute> attribute;

    public ModifiedToolProvider(ItemStack stack) {
        this.stack = stack;
    }

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nullable Capability<T> cap, @Nullable Direction side) {
        if (cap == null)
            return LazyOptional.empty();

        if (cap == CapabilityEnergy.ENERGY) {
            if (energy == null)
                return (energy = LazyOptional.of(() -> new ItemEnergyStorage(stack))).cast();
            else
                return energy.cast();
        }

        if (cap == CapabilityModuleStorage.MODULE_STORAGE) {
            if (module == null)
                return (module = LazyOptional.of(() -> new ItemModuleStorage(stack))).cast();
            else
                return module.cast();
        }

        if (cap == CapabilityModifiedAttribute.ATTRIBUTE) {
            if (attribute == null)
                return (attribute = LazyOptional.of(() -> new ItemModifiedAttribute(stack))).cast();
            else
                return attribute.cast();
        }

        return LazyOptional.empty();
    }
}
